package video;

import video.vo.PropertiesModel;
import video.vo.up.BiliInfoModel;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * 批量下载视频封面...
 * @author 胡琦
 * @date 2022-04-15 星期五 22:41
 */
public class DownloadPictureTest {
    /** B站下载前缀 */
    private final static String BILIBILI_URL_PRE = " https://www.bilibili.com/video/";
    /** 下载器命令前缀 */
    private final static String ANNIE = "annie ";
    /** 生成的bat文件名称 */
    private final static String BAT_FILE_NAME = "\\down.bat";
    /** 需要读取的配置文件名称 */
    private final static String PROPERTIES_NAME = "application.properties";

    /**
     * 下载图片, 以标题名命名
     * @param models
     * @param filePre
     */
    public static void downImages(List<BiliInfoModel> models, String filePre) {
        models = removeWrongful(models);
        List<String> fileName = getPathFileName(filePre);
        models.forEach(x -> {
            try {
                // 已经存在的文件就不重复下载了
                if (!fileName.contains(x.getTitle())) {
                    downImage(x, filePre);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 去除无效字符
     * @param models
     * @return
     */
    private static List<BiliInfoModel> removeWrongful(List<BiliInfoModel> models) {
        return models.stream()
                .map(x -> replaceIllegalCharacter(x, new ArrayList<>(Arrays.asList("\\","/",":","?","\"","/",">","<","|"))))
                .collect(Collectors.toList());
    }

    /**
     * 替换非法字符
     * @param model
     * @param reList
     * @return
     */
    private static BiliInfoModel replaceIllegalCharacter(BiliInfoModel model, List<String> reList) {
        // 使用循环解决, 待看是否有更好的办法
        reList.forEach(x ->  {
            boolean contains = model.getTitle().contains(x);
            if (contains) {
                model.setTitle(model.getTitle().replace(x, "-"));
            }
        });
        return model;
    }

    /**
     * 使用url下载网络图片
     * @param model
     * @param filePre
     * @throws Exception
     */
    private static void downImage(BiliInfoModel model, String filePre) throws Exception {
        //定义一个URL对象，就是你想下载的图片的URL地址
        URL url = new URL(model.getPic());
        //打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为10秒
        conn.setConnectTimeout(10 * 1000);
        //通过输入流获取图片数据
        InputStream is = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(is);
        //创建一个文件对象用来保存图片，默认保存当前工程根目录，起名叫Copy.jpg
        File imageFile = new File(filePre + model.getTitle() + ".jpg");
        File parentFile = imageFile.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        //创建输出流
        try(FileOutputStream outStream = new FileOutputStream(imageFile)) {
            //写入数据
            outStream.write(data);
        }catch (IOException e) {
            System.out.println("error");
            e.printStackTrace();
        }
    }

    /**
     * 读
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * 生成 bat文件
     * @param vlist
     * @param properties
     * @throws IOException
     */
    public static void createBatFile(List<BiliInfoModel> vlist, PropertiesModel properties) throws IOException {
        StringBuilder sb = new StringBuilder();
        vlist.forEach(x -> sb.append(BILIBILI_URL_PRE).append(x.getBvid()));
        // 生成bat文件, 如果文件夹不存在就创建
        File file = new File(properties.getFilePre() + BAT_FILE_NAME);
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(ANNIE + sb);
        fileWriter.flush();
        fileWriter.close();
    }

    /**
     * 读取配置文件, 但是读取转义json这些的时候到程序中读取会有异常, 还不如直接改程序
     * @return
     * @throws IOException
     */
    public static PropertiesModel getProperties() throws IOException {
        Properties pros =  new Properties();
        ClassLoader classLoader = CreateBilibiliDownFileDemo.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream(PROPERTIES_NAME);
        pros.load(is);
        String filePre = pros.getProperty("filePre");
        String json = pros.getProperty("json");
        return PropertiesModel.builder().filePre(filePre).json(json).build();
    }

    /**
     * 获取目标文件夹下面所有文件名
     * @param path
     * @return
     */
    private static List<String> getPathFileName(String path) {
        try {
            return Files.walk(Paths.get(path))
                    .filter(Files::isRegularFile)
                    .map(Path::toFile)
                    .map(File::getName)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            // 可能没有这个目录, 因为是第一次进来
            System.out.println("第一次 path = " + path);
        }
        return new ArrayList<>();
    }
}
